package com.segersten.kalaha

import java.util.logging.Logger;

class PlayerController {

	private static Logger LOG = Logger.getLogger(getClass().getCanonicalName());
	def facebookKeys

	def index = { render(text:"Welcome to the PlayerController")}
	
	def lookupPlayerPoints = {
		if (params.userId == null) {
			response.status = 400
			return
		}
		Player p = getPlayerFromCache(params.userId)
		if (p==null) {
			p = getPlayerFromStorage(params.userId)
		}
		if (p==null) {
			response.status = 400
			return
		}
		int score1 = 0;
		PlayerScoreDay ps1 = SessionTicket.find("SELECT FROM PlayerScoreDay sc WHERE sc.userId = :id", [id:p.userId])
		if (ps1 != null) {
			score1 = ps1.score
		}
		int score2 = 0;
		PlayerScoreDay ps2 = SessionTicket.find("SELECT FROM PlayerScoreWeek sc WHERE sc.userId = :id", [id:p.userId])
		if (ps2 != null) {
			score2 = ps2.score
		}
		int score3 = 0;
		PlayerScoreDay ps3 = SessionTicket.find("SELECT FROM PlayerScoreTotal sc WHERE sc.userId = :id", [id:p.userId])
		if (ps3 != null) {
			score3 = ps3.score
		}
		render(contentType:"text/json") {
			day = score1
			week = score2
			total = score3
		}
	}

	def lookupPlayer = {
		if (params.userId == null) {
			response.status = 400
			return
		}
		Player p = getPlayerFromCache(params.userId)
		if (p==null) {
			p = getPlayerFromStorage(params.userId)
		}
		if (p==null) {
			response.status = 400
			return
		}
		response.setHeader("Cache-Control","max-age=86400")
		render(contentType:"text/json") {
			userId = p.userId
			name = p.name
			type = p.type
			points = "http://"+facebookKeys.callbackDomain + "/players/"+p.userId+"/points"
			ticket = "http://"+facebookKeys.callbackDomain + "/ticketsbyuserid/"+p.userId
		}
	}
	
	private Player getPlayerFromCache(String userId) {
		PlayerCache pc = new PlayerCache()
		return pc.getByUserId(params.userId)
	}
	
	private Player getPlayerFromStorage(String userId) {
		throw new UnsupportedOperationException("Not found, todo implement 'getPlayerFromStorage' " + userId)
	}

}
